package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.query.EmployeeQueryObject;
import cn.wolfcode.crm.service.IEmployeeService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.PageResult;
import cn.wolfcode.crm.util.PermissionName;
import cn.wolfcode.crm.util.UploadUtil;
import com.alibaba.druid.util.StringUtils;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @program: crm
 * @description:
 * @author: Mr.chen
 * @create: 2018-07-07 22:06
 **/
@Controller
@RequestMapping("employee")
public class EmployeeController {
    @Autowired
    private IEmployeeService service;
    @Autowired
    private ServletContext ctx;

    @RequestMapping("")
    @PermissionName("员工主页")
    @RequiresPermissions("employee:index")
    public String index() {
        return "employee/list";
    }

    @RequestMapping("list")
    @ResponseBody
    @RequiresPermissions("employee:list")
    @PermissionName("员工数据")
    public PageResult list(EmployeeQueryObject qo) {
        PageResult result = service.query(qo);
        return result;
    }

    //检查用户是否存在, true表示不存在
    @RequestMapping("validateUsername")
    @ResponseBody
    public boolean validateUsername(String username, Long id) {
        Employee employee = service.checkName(username);
        if (id == null) {
            return employee == null;
        }else{
            return true;
        }
    }

    @RequestMapping("save")
    @ResponseBody
    @RequiresPermissions("employee:save")
    @PermissionName("员工保存")
    public JsonResult save(Employee entity) {
        JsonResult result = new JsonResult();
        try {
            service.save(entity);
        }catch (Exception e){
            e.printStackTrace();
            result = new JsonResult("保存操作失败");
        }
        return result;
    }

    @RequestMapping("update")
    @ResponseBody
    @RequiresPermissions("employee:update")
    @PermissionName("员工更新")
    public JsonResult update(Employee entity, MultipartFile pic) {

        if (pic != null) {
            // 如果当前商品之前有图片,那么旧删除
            if (!StringUtils.isEmpty(entity.getImagePath())) {
                UploadUtil.deleteFile(ctx, entity.getImagePath());
            }
            // 调用工具类中的文件上传方法执行上传操作
            // 获取到文件在项目中的路径
            String realPath =ctx.getRealPath("/upload");
            String imagePath = UploadUtil.upload(pic, realPath);
            entity.setImagePath(imagePath);
        }

        JsonResult result = new JsonResult();
        try {
            service.update(entity);
        }catch (Exception e){
            e.printStackTrace();
            result = new JsonResult("更新操作失败");
        }
        return result;
    }

    @RequestMapping("changeState")
    @ResponseBody
    @RequiresPermissions("employee:changeState")
    @PermissionName("员工状态修改")
    public JsonResult changeState(Long id) {
        JsonResult result = new JsonResult();
        try {
            service.changeState(id);
        } catch (Exception e) {
            e.printStackTrace();
            result = new JsonResult("操作失败");
        }
        return result;
    }

    @RequestMapping("queryEmps")
    @ResponseBody
    @RequiresPermissions("employee:queryEmps")
    @PermissionName("员工下拉框数据")
    public List<Employee> list() {
        List<Employee> list = service.list();
        return list;
    }

    @RequestMapping("personalMessage")
    public Employee personalMessage(Model model) {
        Employee currentUser = (Employee) SecurityUtils.getSubject().getPrincipal();
        Employee employee = service.get(currentUser.getId());
        model.addAttribute("employee",employee);
        return employee;
    }


    @RequestMapping("changePassword")
    public Employee changePassword() {
        Employee employee1 = (Employee) SecurityUtils.getSubject().getPrincipal();
        Employee employee = service.get(employee1.getId());
        return employee;
    }

    @RequestMapping("changeByPassword")
    @ResponseBody
    @RequiresPermissions("employee:changeByPassword")
    @PermissionName("修改员工密码密码")
    public JsonResult changeByPassword(String password) {
        JsonResult result = new JsonResult();
        Employee entity = (Employee) SecurityUtils.getSubject().getPrincipal();
        entity.setPassword(password);
        try {
            service.changeByPassword(entity);
        } catch (Exception e) {
            e.printStackTrace();
            result = new JsonResult("修改密码失败");
        }
        return result;
    }
    //导出
    @RequestMapping("export")
    public void export(HttpServletRequest request, HttpServletResponse response, EmployeeQueryObject qo) throws Exception {
        //文件名
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = sdf.format(new Date()) + ".xls";

        response.setContentType("application/x-excel");
        response.setCharacterEncoding("UTF-8");
        //excel文件名
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

        PageResult pageResult = service.query(qo);


        //List<Employee> list = new ArrayList<>();
        List<Employee> list = (List<Employee>) pageResult.getRows();
        try {
            //1.创建工作簿
            WritableWorkbook workbook = Workbook.createWorkbook(response.getOutputStream());
            //2.创建页签(sheet) 参数一:页签的名称,参数二:索引
            WritableSheet sheet = workbook.createSheet("员工列表", 0);

            //获取到所有前台发出的请求中所带的参数(url和datagrid中的内容)
            String parameter = request.getParameter("titles");
            //前台返回的titles是一个字符串,用spit以","分割,然后封装进数组中
            String[] parameters = parameter.split(",");

            List<String> header = new ArrayList<>();
            for (String s : parameters) {
                s = URLDecoder.decode(s, "UTF-8");
                header.add(s);
            }
            //3.创建一个单元格

            Label label = null;
            for (int i = 1; i < header.size(); i++) {
                label = new Label(i, 0, header.get(i));
                //4.添加到页签中
                sheet.addCell(label);
            }
            for (int i = 1; i < list.size() + 1; i++) {
                // 3.行可变,列直接写死
                Employee employee = list.get(i - 1);
                label = new Label(0, i, (employee.getId()).toString());
                sheet.addCell(label);
                label = new Label(1, i, employee.getUsername());
                sheet.addCell(label);

                label = new Label(2, i, employee.getRealname());
                sheet.addCell(label);

                label = new Label(3, i, employee.getTel());
                sheet.addCell(label);

                label = new Label(4, i, employee.getEmail());
                sheet.addCell(label);

                label = new Label(5, i, employee.getDept().getName());
                sheet.addCell(label);

                label = new Label(6, i, employee.getHiredate().toLocaleString());
                sheet.addCell(label);
                if (employee.getAdmin() == 1) {
                    label = new Label(7, i, "是");

                } else {
                    label = new Label(7, i, "否");
                }
                sheet.addCell(label);

                if (employee.getState() == 0) {
                    label = new Label(8, i, "离职");

                } else {
                    label = new Label(8, i, "在职");
                }
                sheet.addCell(label);
            }
            //5.写出数据
            workbook.write();
            workbook.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
